#transflation
import urllib.request
import urllib.parse
import random
import hashlib
import json
import time

while(True):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    #防止被拉黑
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'

    data = {}

    content =  input('请输入需要翻译的内容(输入!q退出)：')

    #退出程序
    if content == '!q':
        print('程序退出！')
        break
    
    ts = str(time.time() * 1000)
    salt = ts + str(random.randint(1,10))
    sign = hashlib.md5(('fanyideskweb' + content + salt + 'Nw(nmmbP%A-r6U3EUn]Aj').encode('utf-8')).hexdigest()


    data['i'] = content
    data['from'] =  'AUTO'
    data['to'] =  'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = salt
    data['sign'] = sign
    data['lts'] = ts
    data['bv'] = '4f7ca50d9eda878f3f40fb696cce4d6d'
    data['doctype'] =  'json'
    data['versio'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_REALTlME'
    data = urllib.parse.urlencode(data).encode('utf-8')

    req = urllib.request.Request(url, data, head)
    reponse = urllib.request.urlopen(url, data)

    html = reponse.read().decode('utf-8')
    target = json.loads(html)

    print(target['translateResult'][0][0]['tgt'])
    time.sleep(1)
